package com.xxxx.server.controller;

import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.AdminLoginParam;
import com.xxxx.server.pojo.param.AdminParam;
import com.xxxx.server.pojo.param.BackPasswordParam;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.service.MailService;
import com.xzl.tool.util.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 登录
 *
 * @author zhoubin
 * @since 1.0.0
 */
@Api( tags = "登录LoginController")
@RestController
@RequestMapping("/login")
public class LoginController {

	@Autowired
	private IAdminService adminService;

	@Autowired
	private MailService mailService;


	@ApiOperation("登录")
	@PostMapping("/")
	public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request) {
		return adminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
	}


	@ApiOperation("获取当前登录用户信息")
	@GetMapping("/info")
	public RespBean getAdminInfo(Principal principal) {
		if (null == principal)
			return null;
		String username = principal.getName();
		Admin admin = adminService.getUserByUsername(username);
		admin.setPassword(null);
		admin.setRoles(adminService.getRoles(admin.getId()));
		return RespBean.success(admin);
	}

	@ApiOperation("退出登录")
	@PostMapping("/logout")
	public RespBean logout() {
		return RespBean.success("注销成功！");
	}

	@ApiOperation("注册账号")
	@PostMapping("/register")
	public RespBean register(@Validated @RequestBody AdminParam admin,HttpServletRequest request) {
		String userName = adminService.register(admin ,request);
		return RespBean.success("注册成功！",userName);
	}

	/**
	 * 发送纯文本邮件
	 */
	@ApiOperation("发送邮箱验证码")
	@GetMapping("/getEmailCode")
	public RespBean getEmailCode(String email) {
		mailService.getEmailCode(email);
		return RespBean.success();
	}


    @ApiOperation("找回密码")
    @PostMapping("/getBackPassword")
    public RespBean getBackPassword(@RequestBody BackPasswordParam backPasswordParam) {
        adminService.getBackPassword(backPasswordParam);
        return RespBean.success("修改成功！");
    }
}